import useStore from "@/store";
import { Directive, DirectiveBinding } from "vue";

/**
 * v-hasPerm 按钮权限处理
 */
export const hasPerm: Directive = {
  // 自定义mounted钩子函数,在组件挂载到 DOM 上之后执行一些操作
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    // 超级管理员角色
    const { admin } = useStore();
    if (admin.roleList.includes("1")) {
      return true;
    }
    // 其他角色
    const { value } = binding;
    if (value) {
      // 按钮权限标识
      const requiredPerms = value;
      const hasPerm = admin.permissionList?.some((perm) => {
        return requiredPerms.includes(perm);
      });
      if (!hasPerm) {
        // 去除按钮
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error("need perms! Like v-has-perm=\"['system:admin:add','system:admin:edit']\"");
    }
  },
};

/**
 * v-hasRole 角色权限处理
 */
export const hasRole: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    if (value) {
      const requiredRoles = value;
      const { admin } = useStore();
      const hasRole = admin.roleList.some((role) => {
        return requiredRoles.includes(role);
      });
      if (!hasRole) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error("need roles! Like v-has-role=\"['admin','test']\"");
    }
  },
};
